package faa;

import java.util.*;
import faa.users.User;
import agent.*;

public class SecurityManager extends Agent {
	//Data
	private List<SecurityUser> mySecurityUsers = new LinkedList<SecurityUser>();
	private GUI gui = new GUI();
	
	//Constructor
	public SecurityManager() {
		super();
	}
	
	// Messages
	public void msgLogin(String username, String password){
		mySecurityUsers.add(new SecurityUser(username, password));
	}
	
	/** Scheduler.  Determine what action is called for, and do it. */
	protected boolean pickAndExecuteAnAction() {
		for(SecurityUser su:mySecurityUsers){
			//Rule 1
			if(su.getUserSchema() == null){
				aquireSchema(su);
				return true;
			}
			//Rule 3
			if(su.getUser()  == null){
				aquireUser(su);
				return true;
			}
			//Rule 3
			if(su.getUser() != null){
				loginToGUI(su);
				return true;
			}

		}
		return false;
	}

	// Actions
	private void aquireSchema(SecurityUser su){
		UserSchemaLookUp userSchemaLookUp = UserDatabase.LookUpUser(su.getUsername(), su.getPassword());
		if(userSchemaLookUp.getLookUpSucess() == LookUpSucess.CORRECT){
			su.setUserSchema(userSchemaLookUp.getUserSchema());
		} else if(userSchemaLookUp.getLookUpSucess() == LookUpSucess.BAD_USERNAME) {
			print("Username not found!");
		} else if(userSchemaLookUp.getLookUpSucess() == LookUpSucess.BAD_PASSWORD) {
			print("Incorrect password!");
		}

	}

	private void aquireUser(SecurityUser su){
		if(UserFactory.createUser(su.getUserSchema()) == null) {
			//Bad Schema
		} else {
			User newUser = UserFactory.createUser(su.getUserSchema());
			su.setUser (newUser);
		}
	}

	private void loginToGUI(SecurityUser su){
		gui.msgWelcome(su.getUser());
	}

	//Private Classes
	private class SecurityUser{
		String username;
		String password;
		User user;
		UserSchema userSchema;
		public SecurityUser(String username, String password){
			this.username = username;
			this.password = password;
		}
		public String getUsername() {
			return username;
		}
		public void setUsername(String username) {
			this.username = username;
		}
		public String getPassword() {
			return password;
		}
		public void setPassword(String password) {
			this.password = password;
		}
		public User getUser() {
			return user;
		}
		public void setUser(User user) {
			this.user = user;
		}
		public UserSchema getUserSchema() {
			return userSchema;
		}
		public void setUserSchema(UserSchema userSchema) {
			this.userSchema = userSchema;
		}

	}
}
